<template>
  <div class="import-btn">
    <input ref="input" type="file" accept=".xls,.xlsx" @change="change">
    <el-button @click="onImport">
      <slot/>
    </el-button>
  </div>
</template>

<script>
  export default {
    name: 'index',
    props: {
      importMethod: {
        type: Function,
        default() {
        }
      },
      fileName: {
        type: String,
        default: 'file'
      },
      callback: {
        type: Function,
        default: function() {
          if (this.$parent.$refs.dataTable) {
            this.$parent.$refs.dataTable.getDataList()
          }
        }
      }
    },
    data() {
      return {}
    },
    methods: {
      change(e) {
        const file = e.target.files[0]
        this.$confirm(`是否导入${file.name}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const formData = new FormData()
          formData.append(this.fileName, file)
          this.importMethod(formData).then(res => {
            this.empty()
            this.callback()
            this.$notify({
              title: '成功',
              message: '导入成功',
              type: 'success'
            })
          }).catch(e => {
            this.empty()
          })
        }).catch(() => {
          this.empty()
        })
      },
      onImport() {
        this.$refs.input.click()
      },
      empty() {
        this.$refs.input.value = ''
      }
    },
    mounted() {
    }
  }
</script>

<style scoped lang="scss">
  .import-btn {
    display: inline-block;
    margin-left: 10px;

    input {
      display: none;
    }
  }

</style>
